package org.javaweb.cms_web.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 访问日志
 */
@Component
@Aspect
@Slf4j
public class ServiceLogAspect {
    @Pointcut("execution(* org.javaweb.cms_web.*.*.*(..))")
    public void pointcut() {
    }

    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        Object[] args = joinPoint.getArgs();

        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteHost();
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();

        StringBuilder params = new StringBuilder();
        for (Object arg : args) {
            if (arg != null) {
                params.append("[");
                for (java.lang.reflect.Field field : arg.getClass().getDeclaredFields()) {
                    field.setAccessible(true);
                    try {
                        params.append(field.getName()).append("=").append(field.get(arg)).append(", ");
                    } catch (IllegalAccessException e) {
                        log.error("Error accessing field", e);
                    }
                }
                params.append("], ");
            }
        }

        log.info("用户[{}]在[{}],访问了[{}],参数为[{}]", ip, now, target, params.toString());
    }
}
